import {
  Injectable,
  BadRequestException,
  ForbiddenException,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import {
  ShortsListQueryDto,
  ShortsListResponseDto,
  ShortInfoDto,
  ChapterInfoDto,
  SortBy,
} from './dto/shorts.dto';
import {
  CreateShortsOrderDto,
  ShortsOrderResponseDto,
  BatchShortsOrderResponseDto,
} from './dto/shorts-order.dto';
import {
  UpdateWatchProgressDto,
  WatchLogResponseDto,
} from './dto/shorts-watch-log.dto';

@Injectable()
export class ShortsService {
  constructor(private prisma: PrismaService) {}

  /**
   * 获取短剧列表
   */
  async getShortsList(
    query: ShortsListQueryDto,
  ): Promise<ShortsListResponseDto> {
    const {
      page = 1,
      pageSize = 20,
      categoryId,
      directionId,
      status,
      isFree,
      isTop,
      keyword,
      sortBy = SortBy.LATEST,
    } = query;

    // 构建查询条件
    const where: any = {
      isDeleted: false,
      isHidden: false,
    };

    if (categoryId) {
      where.categoryId = categoryId;
    }

    if (directionId) {
      where.directionId = directionId;
    }

    if (status) {
      where.status = status;
    }

    if (typeof isFree === 'boolean') {
      where.isFree = isFree;
    }

    if (typeof isTop === 'boolean') {
      where.isTop = isTop;
    }

    if (keyword) {
      where.OR = [
        { title: { contains: keyword, mode: 'insensitive' } },
        { summary: { contains: keyword, mode: 'insensitive' } },
        { description: { contains: keyword, mode: 'insensitive' } },
      ];
    }

    // 构建排序条件
    let orderBy: any = {};
    switch (sortBy) {
      case SortBy.LATEST:
        orderBy = { createdAt: 'desc' };
        break;
      case SortBy.POPULAR:
        orderBy = { viewCount: 'desc' };
        break;
      case SortBy.VIEW_COUNT:
        orderBy = { viewCount: 'desc' };
        break;
      case SortBy.LIKE_COUNT:
        orderBy = { likeCount: 'desc' };
        break;
      case SortBy.RATING:
        // 这里可以添加评分排序逻辑
        orderBy = { createdAt: 'desc' };
        break;
      default:
        orderBy = { createdAt: 'desc' };
    }

    // 先置顶，再按其他条件排序
    const finalOrderBy = [{ isTop: 'desc' }, orderBy];

    // 查询总数
    const total = await this.prisma.short.count({ where });

    // 查询短剧列表
    const shorts = await this.prisma.short.findMany({
      where,
      orderBy: finalOrderBy,
      skip: (page - 1) * pageSize,
      take: pageSize,
      include: {
        category: {
          select: {
            id: true,
            name: true,
          },
        },
        direction: {
          select: {
            id: true,
            name: true,
          },
        },
      },
    });

    // 转换数据格式
    const list: ShortInfoDto[] = shorts.map((short) => ({
      id: short.id,
      title: short.title,
      coverUrl: short.coverUrl,
      summary: short.summary || undefined,
      instructor: short.instructor,
      viewCount: short.viewCount,
      likeCount: short.likeCount,
      favoriteCount: short.favoriteCount,
      isTop: short.isTop,
      isFree: short.isFree,
      status: short.status,
      shareCount: short.shareCount,
      episodeCount: short.episodeCount,
      totalDuration: short.totalDuration,
      tags: short.tags,
      category: {
        id: short.category.id,
        name: short.category.name,
      },
      direction: {
        id: short.direction.id,
        name: short.direction.name,
      },

      createdAt: short.createdAt.toISOString(),
      updatedAt: short.updatedAt.toISOString(),
    }));

    // 计算分页信息
    const totalPages = Math.ceil(total / pageSize);

    return {
      list,
      pagination: {
        page,
        pageSize,
        total,
        totalPages,
      },
    };
  }

  /**
   * 获取短剧详情
   */
  async getShortDetail(id: number, userId?: number): Promise<ShortInfoDto> {
    const short = await this.prisma.short.findUnique({
      where: {
        id,
        isDeleted: false,
        isHidden: false,
      },
      include: {
        category: {
          select: {
            id: true,
            name: true,
          },
        },
        direction: {
          select: {
            id: true,
            name: true,
          },
        },
        chapters: {
          orderBy: { sort: 'asc' },
          select: {
            id: true,
            title: true,
            description: true,
            coverUrl: true,
            duration: true,
            points: true,
            viewCount: true,
            sort: true,
            videoUrl: true, // 添加videoUrl字段
          },
        },
      },
    });

    if (!short) {
      throw new BadRequestException('短剧不存在');
    }

    // 增加观看次数
    await this.prisma.short.update({
      where: { id },
      data: { viewCount: { increment: 1 } },
    });

    // 检查用户VIP状态和已购买章节（如果提供了userId）
    let isVip = false;
    let purchasedChapterIds: number[] = [];

    if (userId) {
      // 检查VIP状态
      const user = await this.prisma.user.findUnique({
        where: { id: userId },
        select: { vipExpiredAt: true },
      });
      isVip = !!(user?.vipExpiredAt && user.vipExpiredAt > new Date());

      // 检查用户已购买的章节
      const userOrders = await this.prisma.shortsOrder.findMany({
        where: {
          userId,
          shortsId: id,
        },
        select: {
          chapterId: true,
        },
      });
      purchasedChapterIds = userOrders
        .map((order) => order.chapterId)
        .filter((id) => id !== null);
    }

    // 转换数据格式
    return {
      id: short.id,
      title: short.title,
      coverUrl: short.coverUrl,
      summary: short.summary || undefined,
      instructor: short.instructor,
      viewCount: short.viewCount + 1, // 包含本次访问
      likeCount: short.likeCount,
      favoriteCount: short.favoriteCount,
      isTop: short.isTop,
      isFree: short.isFree,
      status: short.status,
      shareCount: short.shareCount,
      episodeCount: short.episodeCount,
      totalDuration: short.totalDuration,
      tags: short.tags,
      category: {
        id: short.category.id,
        name: short.category.name,
      },
      direction: {
        id: short.direction.id,
        name: short.direction.name,
      },
      chapters: short.chapters.map((chapter) => {
        // 如果用户是VIP或已购买该章节，积分显示为0
        let effectivePoints = chapter.points;
        if (isVip || purchasedChapterIds.includes(chapter.id)) {
          effectivePoints = 0;
        }

        // 构建章节数据
        const chapterData: any = {
          id: chapter.id,
          title: chapter.title,
          description: chapter.description || undefined,
          coverUrl: chapter.coverUrl || undefined,
          duration: chapter.duration || undefined,
          points: effectivePoints,
          viewCount: chapter.viewCount,
          sort: chapter.sort,
        };

        // 如果用户未登录且章节积分为0，则返回videoUrl
        if (!userId && chapter.points === 0) {
          chapterData.videoUrl = chapter.videoUrl;
        }

        return chapterData;
      }),
      createdAt: short.createdAt.toISOString(),
      updatedAt: short.updatedAt.toISOString(),
    };
  }

  /**
   * 获取分类列表
   */
  async getCategories() {
    return this.prisma.shortsCategory.findMany({
      where: { id: { not: undefined } },
      select: {
        id: true,
        name: true,
      },
      orderBy: { id: 'asc' },
    });
  }

  /**
   * 获取方向列表
   */
  async getDirections() {
    return this.prisma.shortsDirection.findMany({
      where: { id: { not: undefined } },
      select: {
        id: true,
        name: true,
      },
      orderBy: { id: 'asc' },
    });
  }

  /**
   * 更新用户观看进度
   * 确保每个用户的某个短剧只有一条记录
   */
  async updateWatchProgress(
    userId: number,
    watchDto: UpdateWatchProgressDto,
  ): Promise<WatchLogResponseDto> {
    const { shortsId, chapterId, progress } = watchDto;

    // 检查短剧是否存在
    const shorts = await this.prisma.short.findUnique({
      where: {
        id: shortsId,
        isDeleted: false,
        isHidden: false,
      },
    });

    if (!shorts) {
      throw new BadRequestException('短剧不存在');
    }

    // 检查章节是否存在且属于该短剧
    const chapter = await this.prisma.shortsChapter.findUnique({
      where: {
        id: chapterId,
        shortsId,
      },
    });

    if (!chapter) {
      throw new BadRequestException('章节不存在或不属于该短剧');
    }

    // 查找用户是否已有该短剧的观看记录
    const existingLog = await this.prisma.shortsChapterLog.findFirst({
      where: {
        userId,
        shortsId,
      },
    });

    let watchLog: any;

    if (existingLog) {
      // 如果存在记录，则更新章节ID和进度
      watchLog = await this.prisma.shortsChapterLog.update({
        where: { id: existingLog.id },
        data: {
          chapterId,
          progress,
          timestamp: new Date(),
        },
      });
    } else {
      // 如果不存在记录，则创建新记录
      watchLog = await this.prisma.shortsChapterLog.create({
        data: {
          userId,
          shortsId,
          chapterId,
          progress,
          timestamp: new Date(),
        },
      });
    }

    // 返回更新后的记录
    return {
      id: watchLog.id,
      userId: watchLog.userId,
      shortsId: watchLog.shortsId,
      chapterId: watchLog.chapterId,
      progress: watchLog.progress,
      timestamp: watchLog.timestamp.toISOString(),
    };
  }

  /**
   * 获取用户观看记录
   */
  async getUserWatchLogs(userId: number, shortsId?: number) {
    const where: any = { userId };

    if (shortsId) {
      where.shortsId = shortsId;
    }

    const logs = await this.prisma.shortsChapterLog.findMany({
      where,
      include: {
        shorts: {
          select: {
            title: true,
            coverUrl: true,
          },
        },
        chapter: {
          select: {
            title: true,
            duration: true,
            sort: true,
          },
        },
      },
      orderBy: { timestamp: 'desc' },
    });

    // 获取每个短剧的最大章节排序值
    const shortsIds = [...new Set(logs.map((log) => log.shortsId))];

    // 分别查询每个短剧的最大排序值
    const shortsMaxSortMap = new Map();
    for (const sid of shortsIds) {
      const maxSort = await this.prisma.shortsChapter.aggregate({
        where: { shortsId: sid },
        _max: { sort: true },
      });
      shortsMaxSortMap.set(sid, maxSort._max.sort || 1);
    }

    return logs.map((log) => {
      const maxSort = shortsMaxSortMap.get(log.shortsId) || 1;
      const currentSort = log.chapter.sort || 1;

      // 计算进度：当前章节排序值 / 最大章节排序值
      const progress = Math.round((currentSort / maxSort) * 100);

      return {
        id: log.id,
        userId: log.userId,
        shortsId: log.shortsId,
        chapterId: log.chapterId,
        progress: progress, // 使用计算出的进度值
        timestamp: log.timestamp.toISOString(),
        shorts: {
          title: log.shorts.title,
          coverUrl: log.shorts.coverUrl,
        },
        chapter: {
          title: log.chapter.title,
          duration: log.chapter.duration,
          sort: log.chapter.sort,
        },
      };
    });
  }

  /**
   * 点赞/取消点赞短剧
   */
  async toggleShortsLike(userId: number, likeDto: { shortsId: number }) {
    const { shortsId } = likeDto;

    // 检查短剧是否存在
    const shorts = await this.prisma.short.findUnique({
      where: { id: shortsId },
    });

    if (!shorts) {
      throw new BadRequestException('短剧不存在');
    }

    // 检查用户是否已经点赞过
    const existingLike = await this.prisma.shortsLike.findUnique({
      where: {
        userId_shortsId: {
          userId,
          shortsId,
        },
      },
    });

    if (existingLike) {
      // 如果已经点赞，则取消点赞
      await this.prisma.shortsLike.delete({
        where: { id: existingLike.id },
      });

      // 更新短剧的点赞数量
      await this.prisma.short.update({
        where: { id: shortsId },
        data: { likeCount: { decrement: 1 } },
      });

      return {
        action: 'unliked',
        message: '取消点赞成功',
        isLiked: false,
      };
    } else {
      // 如果没有点赞，则添加点赞
      const like = await this.prisma.shortsLike.create({
        data: {
          userId,
          shortsId,
        },
      });

      // 更新短剧的点赞数量
      await this.prisma.short.update({
        where: { id: shortsId },
        data: { likeCount: { increment: 1 } },
      });

      return {
        action: 'liked',
        id: like.id,
        userId: like.userId,
        shortsId: like.shortsId,
        createdAt: like.createdAt.toISOString(),
        isLiked: true,
      };
    }
  }

  /**
   * 收藏/取消收藏短剧
   */
  async toggleShortsFavorite(
    userId: number,
    favoriteDto: { shortsId: number },
  ) {
    const { shortsId } = favoriteDto;

    // 检查短剧是否存在
    const shorts = await this.prisma.short.findUnique({
      where: { id: shortsId },
    });

    if (!shorts) {
      throw new BadRequestException('短剧不存在');
    }

    // 检查用户是否已经收藏过
    const existingFavorite = await this.prisma.shortsFavorite.findUnique({
      where: {
        userId_shortsId: {
          userId,
          shortsId,
        },
      },
    });

    if (existingFavorite) {
      // 如果已经收藏，则取消收藏
      await this.prisma.shortsFavorite.delete({
        where: { id: existingFavorite.id },
      });

      // 更新短剧的收藏数量
      await this.prisma.short.update({
        where: { id: shortsId },
        data: { favoriteCount: { decrement: 1 } },
      });

      return {
        action: 'unfavorited',
        message: '取消收藏成功',
        isFavorited: false,
      };
    } else {
      // 如果没有收藏，则添加收藏
      const favorite = await this.prisma.shortsFavorite.create({
        data: {
          userId,
          shortsId,
        },
      });

      // 更新短剧的收藏数量
      await this.prisma.short.update({
        where: { id: shortsId },
        data: { favoriteCount: { increment: 1 } },
      });

      return {
        action: 'favorited',
        id: favorite.id,
        userId: favorite.userId,
        shortsId: favorite.shortsId,
        createdAt: favorite.createdAt.toISOString(),
        isFavorited: true,
      };
    }
  }

  /**
   * 获取用户收藏列表
   */
  async getUserFavorites(userId: number, page?: number, pageSize?: number) {
    // 如果不传分页参数，则查询全部
    if (page === undefined || pageSize === undefined) {
      const favorites = await this.prisma.shortsFavorite.findMany({
        where: { userId },
        include: {
          shorts: {
            select: {
              title: true,
              coverUrl: true,
              summary: true,
              instructor: true,
              viewCount: true,
              likeCount: true,
              favoriteCount: true,
              isTop: true,
              isFree: true,
              status: true,
              category: {
                select: {
                  id: true,
                  name: true,
                },
              },
              direction: {
                select: {
                  id: true,
                  name: true,
                },
              },
            },
          },
        },
        orderBy: { createdAt: 'desc' },
      });

      // 转换为DTO格式
      const list = favorites.map((favorite) => ({
        id: favorite.id,
        shortsId: favorite.shortsId,
        title: favorite.shorts.title,
        coverUrl: favorite.shorts.coverUrl,
        summary: favorite.shorts.summary || undefined,
        instructor: favorite.shorts.instructor,
        viewCount: favorite.shorts.viewCount,
        likeCount: favorite.shorts.likeCount,
        favoriteCount: favorite.shorts.favoriteCount,
        isTop: favorite.shorts.isTop,
        isFree: favorite.shorts.isFree,
        status: favorite.shorts.status,
        category: favorite.shorts.category,
        direction: favorite.shorts.direction,
        createdAt: favorite.createdAt.toISOString(),
      }));

      return {
        list,
        pagination: {
          page: 1,
          pageSize: list.length,
          total: list.length,
          totalPages: 1,
        },
      };
    }

    // 如果传了分页参数，则使用分页查询
    const skip = (page - 1) * pageSize;

    // 查询总数
    const total = await this.prisma.shortsFavorite.count({
      where: { userId },
    });

    // 查询收藏列表
    const favorites = await this.prisma.shortsFavorite.findMany({
      where: { userId },
      include: {
        shorts: {
          select: {
            title: true,
            coverUrl: true,
            summary: true,
            instructor: true,
            viewCount: true,
            likeCount: true,
            favoriteCount: true,
            isTop: true,
            isFree: true,
            status: true,
            category: {
              select: {
                id: true,
                name: true,
              },
            },
            direction: {
              select: {
                id: true,
                name: true,
              },
            },
          },
        },
      },
      orderBy: { createdAt: 'desc' },
      skip,
      take: pageSize,
    });

    // 转换为DTO格式
    const list = favorites.map((favorite) => ({
      id: favorite.id,
      shortsId: favorite.shortsId,
      title: favorite.shorts.title,
      coverUrl: favorite.shorts.coverUrl,
      summary: favorite.shorts.summary || undefined,
      instructor: favorite.shorts.instructor,
      viewCount: favorite.shorts.viewCount,
      likeCount: favorite.shorts.likeCount,
      favoriteCount: favorite.shorts.favoriteCount,
      isTop: favorite.shorts.isTop,
      isFree: favorite.shorts.isFree,
      status: favorite.shorts.status,
      category: favorite.shorts.category,
      direction: favorite.shorts.direction,
      createdAt: favorite.createdAt.toISOString(),
    }));

    return {
      list,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize),
      },
    };
  }

  /**
   * 检查用户是否已点赞短剧
   */
  async checkUserLike(userId: number, shortsId: number) {
    const like = await this.prisma.shortsLike.findUnique({
      where: {
        userId_shortsId: {
          userId,
          shortsId,
        },
      },
    });

    return {
      isLiked: !!like,
      likeId: like?.id || null,
    };
  }

  /**
   * 检查用户是否已收藏短剧
   */
  async checkUserFavorite(userId: number, shortsId: number) {
    const favorite = await this.prisma.shortsFavorite.findUnique({
      where: {
        userId_shortsId: {
          userId,
          shortsId,
        },
      },
    });

    return {
      isFavorited: !!favorite,
      favoriteId: favorite?.id || null,
    };
  }

  /**
   * 批量删除短剧收藏
   */
  async batchDeleteFavorites(
    userId: number,
    deleteDto: { shortsIds: number[] },
  ) {
    const { shortsIds } = deleteDto;

    if (!shortsIds || shortsIds.length === 0) {
      throw new BadRequestException('请选择要删除的收藏');
    }

    // 查找用户的所有收藏记录
    const favorites = await this.prisma.shortsFavorite.findMany({
      where: {
        userId,
        shortsId: { in: shortsIds },
      },
      include: {
        shorts: {
          select: {
            id: true,
            title: true,
          },
        },
      },
    });

    if (favorites.length === 0) {
      throw new BadRequestException('未找到要删除的收藏记录');
    }

    // 使用事务批量删除收藏记录
    const result = await this.prisma.$transaction(async (prisma) => {
      const deletedFavorites: any[] = [];
      const failedShortsIds: number[] = [];

      for (const favorite of favorites) {
        try {
          // 删除收藏记录
          await prisma.shortsFavorite.delete({
            where: { id: favorite.id },
          });

          // 更新短剧的收藏数量
          await prisma.short.update({
            where: { id: favorite.shortsId },
            data: { favoriteCount: { decrement: 1 } },
          });

          deletedFavorites.push(favorite);
        } catch (error) {
          console.error(
            `删除收藏失败 - 短剧ID: ${favorite.shortsId}, 错误:`,
            error,
          );
          failedShortsIds.push(favorite.shortsId);
        }
      }

      return { deletedFavorites, failedShortsIds };
    });

    const deletedCount = result.deletedFavorites.length;
    const failedCount = result.failedShortsIds.length;

    let message = `成功删除 ${deletedCount} 个收藏`;
    if (failedCount > 0) {
      message += `，${failedCount} 个删除失败`;
    }

    return {
      deletedCount,
      failedShortsIds: result.failedShortsIds,
      message,
    };
  }

  /**
   * 批量删除观看记录
   */
  async batchDeleteWatchLogs(
    userId: number,
    deleteDto: { watchLogIds: number[] },
  ) {
    const { watchLogIds } = deleteDto;

    if (!watchLogIds || watchLogIds.length === 0) {
      throw new BadRequestException('请选择要删除的观看记录');
    }

    // 查找用户的所有观看记录
    const watchLogs = await this.prisma.shortsChapterLog.findMany({
      where: {
        userId,
        id: { in: watchLogIds },
      },
      include: {
        shorts: {
          select: {
            id: true,
            title: true,
          },
        },
        chapter: {
          select: {
            id: true,
            title: true,
          },
        },
      },
    });

    if (watchLogs.length === 0) {
      throw new BadRequestException('未找到要删除的观看记录');
    }

    // 使用事务批量删除观看记录
    const result = await this.prisma.$transaction(async (prisma) => {
      const deletedWatchLogs: any[] = [];
      const failedWatchLogIds: number[] = [];

      for (const watchLog of watchLogs) {
        try {
          // 删除观看记录
          await prisma.shortsChapterLog.delete({
            where: { id: watchLog.id },
          });

          deletedWatchLogs.push(watchLog);
        } catch (error) {
          console.error(
            `删除观看记录失败 - 记录ID: ${watchLog.id}, 错误:`,
            error,
          );
          failedWatchLogIds.push(watchLog.id);
        }
      }

      return { deletedWatchLogs, failedWatchLogIds };
    });

    const deletedCount = result.deletedWatchLogs.length;
    const failedCount = result.failedWatchLogIds.length;

    let message = `成功删除 ${deletedCount} 条观看记录`;
    if (failedCount > 0) {
      message += `，${failedCount} 条删除失败`;
    }

    return {
      deletedCount,
      failedWatchLogIds: result.failedWatchLogIds,
      message,
    };
  }

  /**
   * 获取随机短剧（包含章节信息）
   */
  async getRandomShorts(params: { count?: number }) {
    const { count = 5 } = params;

    // 构建查询条件
    const where: any = {
      isDeleted: false,
      isHidden: false,
    };

    // 先获取所有符合条件的短剧ID
    const allShortIds = await this.prisma.short.findMany({
      where,
      select: { id: true },
    });

    if (allShortIds.length === 0) {
      return [];
    }

    // 随机选择指定数量的ID
    const shuffledIds = allShortIds
      .sort(() => Math.random() - 0.5)
      .slice(0, Math.min(count, allShortIds.length))
      .map((short) => short.id);

    // 使用随机选择的ID进行查询
    const randomShorts = await this.prisma.short.findMany({
      where: {
        id: { in: shuffledIds },
      },
      include: {
        category: {
          select: {
            id: true,
            name: true,
          },
        },
        direction: {
          select: {
            id: true,
            name: true,
          },
        },
        chapters: {
          select: {
            id: true,
            title: true,
            sort: true,
            duration: true,
            points: true,
            coverUrl: true,
            viewCount: true,
            createdAt: true,
            videoUrl: true, // 添加videoUrl字段
          },
          orderBy: {
            sort: 'asc',
          },
          take: 2, // 只取前2个章节
        },
      },
    });

    // 检查用户VIP状态和已购买章节（如果提供了userId）
    const isVip = false;
    const userPurchasedChapters: Map<number, number[]> = new Map(); // shortsId -> chapterIds[]

    // 格式化返回数据
    return randomShorts.map((short) => ({
      id: short.id,
      title: short.title,
      coverUrl: short.coverUrl,
      summary: short.summary,
      description: short.description,
      instructor: short.instructor,
      viewCount: short.viewCount,
      episodeCount: short.episodeCount,
      totalDuration: short.totalDuration,
      likeCount: short.likeCount,
      favoriteCount: short.favoriteCount,
      isTop: short.isTop,
      isFree: short.isFree,
      status: short.status,
      category: short.category,
      direction: short.direction,
      chapters: short.chapters.map((chapter) => {
        // 如果用户是VIP或已购买该章节，积分显示为0
        let effectivePoints = chapter.points;
        if (
          isVip ||
          userPurchasedChapters.get(short.id)?.includes(chapter.id)
        ) {
          effectivePoints = 0;
        }

        // 构建章节数据
        const chapterData: any = {
          id: chapter.id,
          title: chapter.title,
          sort: chapter.sort,
          duration: chapter.duration,
          points: effectivePoints,
          coverUrl: chapter.coverUrl,
          viewCount: chapter.viewCount,
          createdAt: chapter.createdAt,
        };

        // 如果用户未登录且章节积分为0，则返回videoUrl
        if (chapter.points === 0) {
          chapterData.videoUrl = chapter.videoUrl;
        }

        return chapterData;
      }),
      createdAt: short.createdAt,
      updatedAt: short.updatedAt,
    }));
  }

  /**
   * 获取章节视频URL（检查订单）
   */
  async getChapterVideo(userId: number, shortsId: number, chapterId: number) {
    // 验证短剧和章节是否存在
    const short = await this.prisma.short.findFirst({
      where: {
        id: shortsId,
        isDeleted: false,
        isHidden: false,
      },
      include: {
        chapters: {
          where: {
            id: chapterId,
          },
          select: {
            id: true,
            title: true,
            videoUrl: true,
            points: true,
            coverUrl: true,
            duration: true,
            sort: true,
          },
        },
      },
    });

    if (!short) {
      throw new BadRequestException('短剧不存在');
    }

    if (short.chapters.length === 0) {
      throw new BadRequestException('章节不存在');
    }

    const chapter = short.chapters[0];

    // 检查用户VIP状态
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
      select: {
        vipExpiredAt: true,
      },
    });

    if (!user) {
      throw new BadRequestException('用户不存在');
    }

    // 判断是否为VIP用户（VIP未过期）
    const isVip = !!(user.vipExpiredAt && user.vipExpiredAt > new Date());

    // VIP用户积分变为0，非VIP用户保持原积分
    const effectivePoints = isVip ? 0 : chapter.points;

    // 检查用户是否有购买该章节的订单
    const order = await this.prisma.shortsOrder.findFirst({
      where: {
        userId,
        shortsId,
        chapterId,
      },
    });

    // 如果没有订单，返回错误信息
    if (!order) {
      if (effectivePoints === 0) {
        // 免费章节，提示需要先创建订单
        return {
          shortsId,
          chapterId,
          title: chapter.title,
          coverUrl: chapter.coverUrl,
          duration: chapter.duration,
          sort: chapter.sort,
          originalPoints: chapter.points,
          effectivePoints: 0,
          isFree: true,
          isVip: isVip,
          videoUrl: null,
          orderInfo: null,
          message: isVip ? 'VIP用户需要先创建订单' : '免费章节需要先创建订单',
        };
      } else {
        // 付费章节，提示需要先购买
        return {
          shortsId,
          chapterId,
          title: chapter.title,
          coverUrl: chapter.coverUrl,
          duration: chapter.duration,
          sort: chapter.sort,
          originalPoints: chapter.points,
          effectivePoints: effectivePoints,
          isFree: false,
          isVip: isVip,
          videoUrl: null,
          orderInfo: null,
          message: `需要${effectivePoints}积分购买此章节`,
        };
      }
    }

    // 有订单，返回视频URL和订单信息
    return {
      shortsId,
      chapterId,
      title: chapter.title,
      videoUrl: chapter.videoUrl,
      coverUrl: chapter.coverUrl,
      duration: chapter.duration,
      sort: chapter.sort,
      originalPoints: chapter.points,
      effectivePoints: effectivePoints,
      isFree: effectivePoints === 0,
      isVip: isVip,
      orderInfo: {
        orderId: order.id,
        points: order.points,
        createdAt: order.createdAt,
        status: 'PAID',
      },
      message: '已购买章节',
    };
  }

  /**
   * 创建短剧订单
   */
  async createShortsOrder(
    userId: number,
    createOrderDto: { shortsId: number; chapterIds?: number[] },
  ) {
    const { shortsId, chapterIds } = createOrderDto;

    // 如果没有指定章节ID，则购买整个短剧的所有章节
    let targetChapterIds: number[];
    if (!chapterIds || chapterIds.length === 0) {
      const allChapters = await this.prisma.shortsChapter.findMany({
        where: { shortsId },
        select: { id: true },
        orderBy: { sort: 'asc' },
      });
      targetChapterIds = allChapters.map((ch) => ch.id);
    } else {
      targetChapterIds = chapterIds;
    }

    if (targetChapterIds.length === 0) {
      throw new BadRequestException('短剧没有可购买的章节');
    }

    // 验证短剧是否存在
    const short = await this.prisma.short.findFirst({
      where: {
        id: shortsId,
        isDeleted: false,
        isHidden: false,
      },
    });

    if (!short) {
      throw new BadRequestException('短剧不存在');
    }

    // 验证所有章节是否存在且属于该短剧
    const chapters = await this.prisma.shortsChapter.findMany({
      where: {
        id: { in: targetChapterIds },
        shortsId,
      },
      select: {
        id: true,
        title: true,
        points: true,
        videoUrl: true, // 添加videoUrl字段
      },
    });

    if (chapters.length !== targetChapterIds.length) {
      throw new BadRequestException('部分章节不存在或不属于该短剧');
    }

    // 检查用户VIP状态和积分
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
      select: {
        vipExpiredAt: true,
        points: true,
      },
    });

    if (!user) {
      throw new BadRequestException('用户不存在');
    }

    // 判断是否为VIP用户（VIP未过期）
    const isVip = !!(user.vipExpiredAt && user.vipExpiredAt > new Date());

    // 计算总积分需求
    const totalPoints = chapters.reduce((sum, chapter) => {
      const effectivePoints = isVip ? 0 : chapter.points;
      return sum + effectivePoints;
    }, 0);

    // 检查是否已有订单
    const existingOrders = await this.prisma.shortsOrder.findMany({
      where: {
        userId,
        shortsId,
        chapterId: { in: targetChapterIds },
      },
      include: {
        chapter: {
          select: {
            id: true,
            title: true,
            points: true,
            videoUrl: true,
            coverUrl: true,
          },
        },
      },
    });

    if (existingOrders.length > 0) {
      // 如果存在购买记录，返回这些记录
      return {
        totalPoints: 0,
        orders: existingOrders.map((order) => ({
          orderId: order.id,
          userId: order.userId,
          shortsId: order.shortsId,
          chapterId: order.chapterId,
          points: order.points,
          progress: order.progress,
          status: 'PAID',
          createdAt: order.createdAt.toISOString(),
          chapterTitle: order.chapter?.title,
          videoUrl: order.chapter?.videoUrl,
          coverUrl: order.chapter?.coverUrl,
        })),
        isVip: false,
        message: '以下章节已购买',
        existingOrders: true,
      };
    }

    // 检查用户积分是否足够（非VIP用户）
    if (!isVip && user.points < totalPoints) {
      throw new ForbiddenException(
        `积分不足，需要${totalPoints}积分，当前只有${user.points}积分`,
      );
    }

    // 创建订单
    try {
      const result = await this.prisma.$transaction(async (prisma) => {
        // 扣除用户积分（VIP用户扣除0积分）
        if (!isVip) {
          await prisma.user.update({
            where: { id: userId },
            data: {
              points: { decrement: totalPoints },
            },
          });
        }

        // 为每个章节创建订单
        const orders: any[] = [];
        for (const chapter of chapters) {
          const effectivePoints = isVip ? 0 : chapter.points;
          const order = await prisma.shortsOrder.create({
            data: {
              userId,
              shortsId,
              chapterId: chapter.id,
              points: effectivePoints,
              progress: 0,
            },
          });
          orders.push(order);
        }

        return orders;
      });

      // 更新短剧的观看次数
      await this.prisma.short.update({
        where: { id: shortsId },
        data: { viewCount: { increment: 1 } },
      });

      // 更新所有章节的观看次数
      for (const chapterId of targetChapterIds) {
        await this.prisma.shortsChapter.update({
          where: { id: chapterId },
          data: { viewCount: { increment: 1 } },
        });
      }

      // 重新查询订单数据，包含chapter关联
      const ordersWithChapter = await this.prisma.shortsOrder.findMany({
        where: {
          id: { in: result.map(order => order.id) },
        },
        include: {
          chapter: {
            select: {
              id: true,
              title: true,
              points: true,
              videoUrl: true,
            },
          },
        },
      });

      return {
        totalPoints,
        orders: ordersWithChapter.map((order) => ({
          orderId: order.id,
          userId: order.userId,
          shortsId: order.shortsId,
          chapterId: order.chapterId,
          points: order.points,
          progress: order.progress,
          status: 'PAID',
          videoUrl: order.chapter?.videoUrl, // 现在可以正确获取videoUrl
          createdAt: order.createdAt.toISOString(),
        })),
        isVip,
        message: isVip ? 'VIP用户免费购买成功' : '购买成功',
      };
    } catch (error) {
      throw new ForbiddenException('创建订单失败，请稍后重试');
    }
  }

  /**
   * 创建广告订单
   */
  async createAdOrder(
    userId: number,
    createAdOrderDto: { shortsId: number; chapterId: number },
  ) {
    const { shortsId, chapterId } = createAdOrderDto;

    // 验证短剧是否存在
    const short = await this.prisma.short.findFirst({
      where: {
        id: shortsId,
        isDeleted: false,
        isHidden: false,
      },
    });

    if (!short) {
      throw new BadRequestException('短剧不存在');
    }

    // 验证章节是否存在且属于该短剧
    const chapter = await this.prisma.shortsChapter.findFirst({
      where: {
        id: chapterId,
        shortsId,
      },
      select: {
        id: true,
        title: true,
        videoUrl: true,
        coverUrl: true,
        points: true,
      },
    });

    if (!chapter) {
      throw new BadRequestException('章节不存在或不属于该短剧');
    }

    // 检查用户是否已经购买过该章节（任何类型的订单）
    const existingOrder = await this.prisma.shortsOrder.findFirst({
      where: {
        userId,
        chapterId,
      },
    });

    if (existingOrder) {
      // 如果已有订单，直接返回视频URL
      return {
        id: existingOrder.id,
        userId: existingOrder.userId,
        shortsId: existingOrder.shortsId,
        chapterId: existingOrder.chapterId,
        videoUrl: chapter.videoUrl,
        chapterTitle: chapter.title,
        type: existingOrder.type,
        points: existingOrder.points,
        coverUrl: chapter.coverUrl,
        createdAt: existingOrder.createdAt.toISOString(),
        message: existingOrder.type === 'AD' ? '广告订单已存在，可观看视频' : '您已经购买过该章节',
      };
    }

    // 创建广告订单（不扣除积分）
    const adOrder = await this.prisma.shortsOrder.create({
      data: {
        userId,
        shortsId,
        chapterId,
        points: 0, // 广告订单不扣除积分
        progress: 0,
        type: 'AD', // 设置为广告类型
      },
    });

    // 更新章节的观看次数
    await this.prisma.shortsChapter.update({
      where: { id: chapterId },
      data: { viewCount: { increment: 1 } },
    });

    return {
      id: adOrder.id,
      userId: adOrder.userId,
      shortsId: adOrder.shortsId,
      chapterId: adOrder.chapterId,
      videoUrl: chapter.videoUrl,
      chapterTitle: chapter.title,
      type: adOrder.type,
      points: adOrder.points,
      createdAt: adOrder.createdAt.toISOString(),
      message: '广告订单创建成功，可观看视频',
    };
  }
}
